using System.Collections.Generic;
using SqlQueryBuilder.Clauses;
using SqlQueryBuilder.Util;

namespace SqlQueryBuilder.Criterias
{
    /// <summary>
    /// Update Criteria
    /// </summary>
    public class UpdateCriteria : ICriteria
    {
        #region Properties

        private readonly string tableName;

        /// <summary>
        /// Gets or sets the update clauses.
        /// </summary>
        /// <value>The update clauses.</value>
        public List<UpdateClause> updateClauses { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="UpdateCriteria"/> class.
        /// </summary>
        public UpdateCriteria(string tableName)
        {
            updateClauses = new List<UpdateClause>();
            this.tableName = tableName;
        }

        #endregion
        
        #region ICriteria Members

        /// <summary>
        /// Builds the criteria.
        /// </summary>
        /// <returns></returns>
        public string BuildCriteria()
        {
            return string.Format("UPDATE {0} SET {1}", 
                tableName, 
                GenerateUpdateClause());
        }

        #endregion

        /// <summary>
        /// Generates the update clause.
        /// </summary>
        /// <returns></returns>
        private string GenerateUpdateClause()
        {
            bool firstClause = true;
            string update = string.Empty;
            foreach (UpdateClause updateClause in updateClauses)
            {
                if (firstClause)
                    firstClause = false;
                else
                    update = SqlMultipleFields.AddSeparator(update);

                update += updateClause.BuildUpdateClause();
            }
            return update;
        }
    }
}